//
//  FavoriteSidebarController.m
//
//  Created by Ben Clark-Robinson on 24/03/10.
//  Copyright 2010 Ben Clark-Robinson. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining
//	a copy of this software and associated documentation files (the
//																'Software'), to deal in the Software without restriction, including
//	without limitation the rights to use, copy, modify, merge, publish,
//	distribute, sublicense, and/or sell copies of the Software, and to
//	permit persons to whom the Software is furnished to do so, subject to
//	the following conditions:
//
//	The above copyright notice and this permission notice shall be
//	included in all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
//	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//	IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//	CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//	TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//	SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#import "FavoriteSidebarController.h"


@implementation FavoriteSidebarController

- (id)init
{
    self = [super init];
    if (nil != self) 
    {
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults addObserver:self
                   forKeyPath:UDK_SyncPath 
                      options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                      context:NULL];
        
        [self setPlaceInSidebar:YES];
    }
    
    return self;
}

- (void)dealloc
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObserver:self
				  forKeyPath:UDK_SyncPath];

    
    [super dealloc];

}

- (void)observeValueForKeyPath:(NSString *)keyPath
					  ofObject:(id)object 
                        change:(NSDictionary *)change
                       context:(void *)context
{
    [self setPlaceInSidebar:YES];
}

- (void)awakeFromNib 
{
    [self setPlaceInSidebar:YES];    
}

- (NSURL *)appURL
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSString* sndaCertificate = [defaults stringForKey:UDK_SndaCertificate];
    NSString* syncPath = [defaults stringForKey:UDK_SyncPath];
    NSFileManager* fileManager = [[[NSFileManager alloc] init] autorelease];
    if (fileManager 
        && syncPath && [syncPath length] > 0 && [[syncPath lastPathComponent] isEqualToString:@"EverBox"]
        && sndaCertificate && [sndaCertificate length] > 0 )
    {
        if ( [fileManager fileExistsAtPath:syncPath] ) 
        {
            return [NSURL fileURLWithPath:syncPath];
        }
    } 

    return nil;

}

- (BOOL)placeInSidebar 
{
    NSURL* url = [self appURL];
    if (url)
    {
        return [self willPlaceInSidebar:url];
    }
    else
    {
        return FALSE;
    }
}

- (BOOL)willPlaceInSidebar:(NSURL *)itemURL 
{
    if (nil == itemURL) 
        return FALSE;

    Boolean foundIt=false;
    LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListFavoriteItems, NULL);
    if (loginItems) {
        UInt32 seed = 0U;
        NSArray *currentLoginItems = [NSMakeCollectable(LSSharedFileListCopySnapshot(loginItems, &seed)) autorelease];
        for (id itemObject in currentLoginItems) {
            LSSharedFileListItemRef item = (LSSharedFileListItemRef)itemObject;
			
            UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
            CFURLRef URL = NULL;
            OSStatus err = LSSharedFileListItemResolve(item, resolutionFlags, &URL, /*outRef*/ NULL);
            if (err == noErr) {
                foundIt = CFEqual(URL, itemURL);
                CFRelease(URL);
				
                if (foundIt)
                    break;
            }
        }
        CFRelease(loginItems);
    }
    return (BOOL)foundIt;
}

- (void)setPlaceInSidebar:(BOOL)enabled {
//    [self willChangeValueForKey:@"startAtLogin"];
    NSURL* url = [self appURL];
    if (url) 
    {
        [self setPlaceInSidebar:url enabled:enabled];
    }
//    [self didChangeValueForKey:@"startAtLogin"];
}


- (void)setPlaceInSidebar:(NSURL *)itemURL enabled:(BOOL)enabled 
{
    if (nil == itemURL) 
        return;

    LSSharedFileListItemRef existingItem = NULL;
    LSSharedFileListItemRef preItem = NULL;
	
    LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListFavoriteItems, NULL);
    if (loginItems) {
        UInt32 seed = 0U;
        BOOL bFound = FALSE;
        NSArray *currentLoginItems = [NSMakeCollectable(LSSharedFileListCopySnapshot(loginItems, &seed)) autorelease];
        for (id itemObject in currentLoginItems) 
        {
            LSSharedFileListItemRef item = (LSSharedFileListItemRef)itemObject;
			
            UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
            CFURLRef URL = NULL;
            OSStatus err = LSSharedFileListItemResolve(item, resolutionFlags, &URL, /*outRef*/ NULL);
            if (err == noErr)
            {
                Boolean foundIt = CFEqual(URL, itemURL);
				
                if (foundIt) 
                {
                    existingItem = item;
                    bFound = TRUE;
                    //break;
                }
                CFRelease(URL);
               
                if (enabled && ! foundIt) 
                {
                    NSString* urlLastComponent = [(NSURL*)URL lastPathComponent];
                    NSString* itemURLLastComponent = [itemURL lastPathComponent];
                    if ([urlLastComponent isEqualToString:itemURLLastComponent])
                    {
                        LSSharedFileListItemRemove(loginItems, item);
                    }
                }
            }
            
            if (!bFound) 
            {
                preItem = item;
            }
        }
		
        if (enabled ) 
        {
            if ( existingItem == NULL) 
            {
                LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst,
                                              NULL, NULL, (CFURLRef)itemURL, NULL, NULL);
            }else if ( preItem == NULL)
            {
                LSSharedFileListItemRemove(loginItems, existingItem);
                LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst,
                                              NULL, NULL, (CFURLRef)itemURL, NULL, NULL);
            }
            else
            {
                LSSharedFileListItemRemove(loginItems, existingItem);
                LSSharedFileListInsertItemURL(loginItems, preItem,
                                              NULL, NULL, (CFURLRef)itemURL, NULL, NULL);
            }
 			
        } else if (!enabled && (existingItem != NULL))
            LSSharedFileListItemRemove(loginItems, existingItem);
		
        CFRelease(loginItems);
    }       
}


@end
